package com.cicdi;


import com.cicdi.util.StringUtil;
import com.cicdi.util.Web3jUtil;
import com.platon.protocol.Web3j;
import com.platon.protocol.core.DefaultBlockParameterName;
import com.platon.protocol.core.methods.response.PlatonBlock;
import com.platon.protocol.http.HttpService;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.control.*;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author haypo
 * @date 2021/3/2
 */
public class MainController {

    public TextField nodeAddress;
    public TextArea monitorLogArea;
    public Button monitorStartButton;





    public void startMonitor(ActionEvent actionEvent) {
        if (!monitorStartButton.isDisable()) {
            monitorStartButton.setDisable(true);
        }
        String s = nodeAddress.getText();
        if (StringUtil.isBlank(s)) {
            Alert a = new Alert(Alert.AlertType.ERROR);
            a.setContentText("节点为空");
            a.show();
            monitorStartButton.setDisable(false);
            return;
        }
        if (!s.startsWith("http://")) {
            s = "http://" + s;
        }
        Alert warning = new Alert(Alert.AlertType.WARNING);
        warning.setContentText("节点可能掉线或无法访问");
        Web3j web3j = Web3j.build(new HttpService(s));
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    try {
                        PlatonBlock.Block block = web3j.platonGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock();
                        monitorLogArea.appendText(new Date(System.currentTimeMillis()) + "\t" + "节点在线，块高：" + block.getNumber() + "\n");
                    } catch (Exception e) {
                        t.cancel();
                        monitorStartButton.setDisable(false);
                        monitorLogArea.appendText(new Date(System.currentTimeMillis()) + "\t" + "节点掉线或无法访问" + "\n");
                        if (!warning.isShowing()) {
                            warning.showAndWait();
                        }
                    }
                });
            }
        }, 100, 10000);
    }
}
